package com.soundai.skill.helloworld.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.Slot;
import com.amazon.ask.model.canfulfill.CanFulfillIntent;
import com.amazon.ask.model.canfulfill.CanFulfillIntentValues;
import com.amazon.ask.response.ResponseBuilder;
import com.soundai.skill.helloworld.Service.JedisUtil;
import com.soundai.skill.helloworld.Service.WisdomHomeService;
import com.soundai.skill.helloworld.log.logC;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

import java.util.Optional;

import static com.amazon.ask.request.Predicates.intentName;

public class ChatIntentHandler implements IntentRequestHandler {
    @Override
    public boolean canHandle(HandlerInput handlerInput, IntentRequest intentRequest) {
        //intentRequest.getIntent().getSlots().
        //return handlerInput.matches(intentName("chat"));
        if (intentRequest.getType().equals("IntentRequest"))
            return handlerInput.matches(intentName(intentRequest.getIntent().getName()));
        else
            return handlerInput.matches(intentName("chat"));
        //return handlerInput.matches(intentName(intentRequest.getIntent().getName()));
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput, IntentRequest intentRequest) {
        logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"开始intentRequest时间："+logC.getCurrentYYYYMMDDHHMMSS()+"\r\n");
        logC.writeFile("","handlerInput:"+handlerInput.toString()+"****请求内容:"+intentRequest.toString()+"\r\n");
        String deviceid=handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"speek";
        Slot slot = intentRequest.getIntent().getSlots().get("SlotName");
        String v = slot.getValue();
        JSONObject objV = JSONObject.fromObject(v);
        //String speek = objV.get("query").toString();
        JSONObject returnMsg = new JSONObject();
        String speek="";

        try {
            //String state=logC.teststate;

            String state="";
            Boolean MultiSession=Boolean.TRUE;
            if (JedisUtil.getInstance().get(deviceid)!=null)
                state=JedisUtil.getInstance().get(deviceid).toString();
            logC.writeFile("",deviceid+"缓存数据："+state);
            JedisUtil.getInstance().set(deviceid,"");
            if (state.length()>5) {
                JSONObject objstate = JSONObject.fromObject(state);
                state= objstate.get("speek").toString();
                ResponseBuilder response=handlerInput.getResponseBuilder();
                if (objstate.get("MultiSession")!=null)
                {
                    if (objstate.getString("MultiSession").equals("true"))
                        response.withShouldEndSession(Boolean.FALSE);
                }
                response.withSpeech(state);
                logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+logC.getCurrentYYYYMMDDHHMMSS() +MultiSession+ "播报文字为："+state);
                return response.build();
                //return handlerInput.getResponseBuilder().withSpeech(state).build();
                /*JSONObject objstate = JSONObject.fromObject(state);
                    if (objstate.get("action").equals("tts")) {
                        JedisUtil.getInstance().set(deviceid, "");
                        String[] ss = objstate.get("data").toString().split("@");
                    if (ss.length > 1)
                        speek = ss[1];
                    return handlerInput.getResponseBuilder().withSpeech(speek).build();
                }*/
            }

            logC.writeFile("",deviceid+"直接触发了chat："+objV.get("query").toString());
            JSONObject msg=new JSONObject();
            msg.put("query",objV.get("query").toString());
            msg.put("realm",intentRequest.getIntent().getName());
            returnMsg = WisdomHomeService.requestSound(handlerInput, msg.toString());
            ResponseBuilder response=handlerInput.getResponseBuilder();
            if (returnMsg.getString("sucess").equals("true"))
                speek=returnMsg.getString("speek");
            else
                speek = objV.get("answer").toString();
            if (returnMsg.get("MultiSession")!=null)
            {
                if (returnMsg.getString("MultiSession").equals("true"))
                    response.withShouldEndSession(Boolean.FALSE);
            }
            response.withSpeech(speek);
            logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+logC.getCurrentYYYYMMDDHHMMSS() + "播报文字为："+speek);
            return response.build();//handlerInput.getResponseBuilder().withSpeech(speek).build();
        }  catch (Exception ex)
        {
            speek = objV.get("answer").toString();
            logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"出现异常："+logC.getCurrentYYYYMMDDHHMMSS() + speek+"播报文字为："+ex.toString());
            ResponseBuilder response=handlerInput.getResponseBuilder();
            response.withSpeech(speek);
            return response.build();
            //return handlerInput.getResponseBuilder().withSpeech(speek).build();
        }
    }



   /* @Override
    public Optional<Response> handle(HandlerInput handlerInput) {
        //Jedis jedis = new Jedis("localhost");
        //System.out.println("连接成功");
        //查看服务是否运行
       // System.out.println("服务正在运行: "+jedis.ping());


        //System.out.println("获取到要输出的文本值为："+data.get("todo").toString());

        *//*if(speek.indexOf("买") >=0  || speek.indexOf("购买") >= 0 || speek.indexOf("订") >= 0 || speek.indexOf("来") >= 0){
            speek = "您已购买商品成功，请等待发货";
        }*//*

        logC.writeFile("","响应技能时间："+logC.getCurrentYYYYMMDDHHMMSS()+",,handlerInput:"+handlerInput.getRequestEnvelope() + "：：播报文字为：：");
        //String temp=handlerInput.getRequest().ge
        String temp=handlerInput.getRequestEnvelopeJson().get("SlotName").toString();
        temp="";
       return handlerInput.getResponseBuilder()
                .withSpeech("测试内容")
                .withSimpleCard("chat", handlerInput.getRequest().toString())
                .build();
    }*/
}
